#!/usr/bin/python
# -*- coding: UTF-8 -*-
from socket import *
import time
COD = 'utf-8'
# 获取本地主机名(2选1)
HOST = '127.0.0.1'  # 服务器主机IP
host = gethostname()
# 服务器端端口号
PORT = 21566
BUFSIZ = 1024
ADDR = (HOST, PORT)
SIZE = 10
# 创建 socket 对象
tcpS = socket(AF_INET, SOCK_STREAM)
# 加入socket配置，重用IP和端口
tcpS.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 绑定IP和端口号
tcpS.bind(ADDR)
# 设置最大链接数
tcpS.listen(SIZE)
while True:
    print("服务器启动,监听客户端链接")
    conn, addr = tcpS.accept()
    print("链接的客户端:", addr)
    while True:
        try:
            # 读取已链接客户的发送消息
            data = conn.recv(BUFSIZ)
            # print(type(data))
        except Exception:
            print("断开的客户端:", addr)
            break
        print("接收来自客户端发送的消息:", data.decode(COD))
        if not data:
            break
        # 获取结构化时间戳
        msg = time.strftime("%Y-%m-%d %X")
        msg1 = '服务器回复给客户端的消息->[%s]:%s' %(msg, data.decode(COD))
        # 发送消息给已链接的客户端
        conn.send(msg1.encode(COD))
    # 关闭客户端链接
    conn.close()
tcpS.close()